package test.solr;

import java.io.IOException;
import java.util.function.Consumer;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.util.NamedList;

public class MoreLikeThis {
	
	public static void component() {
		HttpSolrClient client = new HttpSolrClient("http://localhost:8080/solr");
		SolrQuery query = new SolrQuery("id:106");
		query.setParam("mlt", true);
		query.setParam("mlt.fl", "title,text");
		query.setParam("mlt,count", "10");
		try {
			QueryResponse qr = client.query("core2", query);
			System.out.println(qr.getQTime());
			System.out.println(qr.getElapsedTime());
			NamedList<Object> nl = qr.getResponse();
			@SuppressWarnings("rawtypes")
			NamedList mlt = (NamedList) nl.get("moreLikeThis");
			SolrDocumentList docList = (SolrDocumentList)mlt.get("106");
			System.out.println(docList);
			docList.forEach(new Consumer<SolrDocument>() {
				public void accept(SolrDocument t) {
					String id = t.get("id").toString();
					System.out.println(id + "--->" + t.get("title"));
//					float score = (Float)t.get("score");
//					System.out.println(score);
				};
			});
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void handler() {
		HttpSolrClient client = new HttpSolrClient("http://localhost:8080/solr");
		SolrQuery query = new SolrQuery("id:106");
		query.setRequestHandler("/mlt");
//		query.setParam("mlt", true);
		query.setParam("mlt.fl", "title,text");
//		query.setParam("mlt,count", "10");
		try {
			QueryResponse qr = client.query("core2", query);
			System.out.println(qr);
		} catch (SolrServerException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) {
		handler();
	}

}
